package com.example.wenqujingdian.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.example.wenqujingdian.activity.HomeActivity;

/**
 * Create by kxliu on 2018/11/21
 */
public class NetWorkUtils {
    //    public static boolean networkAvailable;
    private static NetWorkUtils INSTANCE;
    public NetConnectivityReceiver networkReceiver;

    /**
     * 检查网络是否可用
     *
     * @return
     */
    //debug网络状态
    public static boolean isNetworkAvailable(Context context) {
        if (Lsetting.debug) {
            ToastUtil.show("debug模式: 网络状态设置为: "+Lsetting.online);
            return Lsetting.online;
        }
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }


    public static NetWorkUtils getInstance() {
        if (INSTANCE == null) INSTANCE = new NetWorkUtils();
        return INSTANCE;
    }

    /**
     * 开启网络连接追踪1
     */
    public void startConnectionTrack(@NonNull Context context) {
        if (networkReceiver == null) {
            networkReceiver = new NetConnectivityReceiver();
        }
        // Registers BroadcastReceiver to track network connection changes.
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(networkReceiver, filter);
    }

    /**
     * 关闭网络连接追踪
     */
    public void stopConnectionTrack(@NonNull Context context) {
        if (networkReceiver == null) return;
        context.unregisterReceiver(networkReceiver);
    }

    private class NetConnectivityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
                Toast.makeText(context, "网络已关闭", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "网络已开启", Toast.LENGTH_LONG).show();
            }
            HomeActivity.networkChanged = true;
            Intent intent1 = new Intent(context, HomeActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent1);
        }
    }
}
